package financialStatistics

import (
	"context"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"insighttracking/apps/admin/auth"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"
	"insighttracking/common/utils"
	"insighttracking/query/service"
	"net/http"
	"os"
)

type ApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ApiLogic {
	hostname, _ := os.Hostname()
	return &ApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ApiLogic) IncomeApi(req *types.IncomeReq) (resp *types.FinanceList, err error) {
	resp = &types.FinanceList{}
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return
	}
	startDate := utils.DateStrToTime(req.StartDate)
	endDate := utils.DateStrToTime(req.EndDate)
	entities, err := service.FinancialStatistics.GetIncomeApi(l.ctx, accountInfo.EnterpriseId, startDate, endDate, req.CustomerID)
	if err != nil {
		return
	}
	list := make([]*types.FinancialStatisticsModel, 0)
	for _, entity := range entities {
		list = append(list, &types.FinancialStatisticsModel{
			CustomerID:   entity.CustomerID,
			CustomerName: entity.CustomerName,
			Code:         entity.ID,
			Amount:       entity.Amount,
			CreatedAt:    utils.TimestampToString(entity.CreatedAt),
		})
	}
	resp.List = list
	return
}

func (l *ApiLogic) ExpensesApi(req *types.ExpensesReq) (resp *types.FinanceList, err error) {
	resp = &types.FinanceList{}
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return
	}
	startDate := utils.DateStrToTime(req.StartDate)
	endDate := utils.DateStrToTime(req.EndDate)
	entities, err := service.FinancialStatistics.GetExpensesApi(l.ctx, accountInfo.EnterpriseId, startDate, endDate, req.SupplierID)
	if err != nil {
		return
	}
	list := make([]*types.FinancialStatisticsModel, 0)
	for _, entity := range entities {
		list = append(list, &types.FinancialStatisticsModel{
			SupplierID:   entity.SupplierID,
			SupplierName: entity.SupplierName,
			Code:         entity.ID,
			Amount:       entity.Amount,
			CreatedAt:    utils.TimestampToString(entity.CreatedAt),
		})
	}
	resp.List = list
	return
}
